# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# Code generated by the Google Gen AI SDK generator DO NOT EDIT.

import functools
import json
import logging
from typing import Any, Iterator, Optional, Union
from urllib.parse import urlencode

from google.genai import _api_module
from google.genai import _common
from google.genai._common import get_value_by_path as getv
from google.genai._common import set_value_by_path as setv
from google.genai.pagers import AsyncPager, Pager

from . import types


logger = logging.getLogger("vertexai_genai.memoryrevisions")

logger.setLevel(logging.INFO)


def _GetAgentEngineMemoryRevisionRequestParameters_to_vertex(
    from_object: Union[dict[str, Any], object],
    parent_object: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
    to_object: dict[str, Any] = {}
    if getv(from_object, ["name"]) is not None:
        setv(to_object, ["_url", "name"], getv(from_object, ["name"]))

    if getv(from_object, ["config"]) is not None:
        setv(to_object, ["config"], getv(from_object, ["config"]))

    return to_object


def _ListAgentEngineMemoryRevisionsConfig_to_vertex(
    from_object: Union[dict[str, Any], object],
    parent_object: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
    to_object: dict[str, Any] = {}

    if getv(from_object, ["page_size"]) is not None:
        setv(parent_object, ["_query", "pageSize"], getv(from_object, ["page_size"]))

    if getv(from_object, ["page_token"]) is not None:
        setv(parent_object, ["_query", "pageToken"], getv(from_object, ["page_token"]))

    if getv(from_object, ["filter"]) is not None:
        setv(parent_object, ["_query", "filter"], getv(from_object, ["filter"]))

    return to_object


def _ListAgentEngineMemoryRevisionsRequestParameters_to_vertex(
    from_object: Union[dict[str, Any], object],
    parent_object: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
    to_object: dict[str, Any] = {}
    if getv(from_object, ["name"]) is not None:
        setv(to_object, ["_url", "name"], getv(from_object, ["name"]))

    if getv(from_object, ["config"]) is not None:
        setv(
            to_object,
            ["config"],
            _ListAgentEngineMemoryRevisionsConfig_to_vertex(
                getv(from_object, ["config"]), to_object
            ),
        )

    return to_object


class MemoryRevisions(_api_module.BaseModule):

    def get(
        self,
        *,
        name: str,
        config: Optional[types.GetAgentEngineMemoryRevisionConfigOrDict] = None,
    ) -> types.MemoryRevision:
        """
        Gets an agent engine memory revision.

        Args:
            name (str): Required. The name of the Agent Engine memory revision to get. Format:
                `projects/{project}/locations/{location}/reasoningEngines/{resource_id}/memories/{memory_id}/revisions/{revision_id}`.
            config (GetAgentEngineMemoryRevisionConfig):
                Optional. Additional configurations for getting the Agent Engine memory revision.

        Returns:
            AgentEngineMemoryRevision: The requested Agent Engine memory revision.

        """

        parameter_model = types._GetAgentEngineMemoryRevisionRequestParameters(
            name=name,
            config=config,
        )

        request_url_dict: Optional[dict[str, str]]
        if not self._api_client.vertexai:
            raise ValueError("This method is only supported in the Vertex AI client.")
        else:
            request_dict = _GetAgentEngineMemoryRevisionRequestParameters_to_vertex(
                parameter_model
            )
            request_url_dict = request_dict.get("_url")
            if request_url_dict:
                path = "{name}".format_map(request_url_dict)
            else:
                path = "{name}"

        query_params = request_dict.get("_query")
        if query_params:
            path = f"{path}?{urlencode(query_params)}"
        # TODO: remove the hack that pops config.
        request_dict.pop("config", None)

        http_options: Optional[types.HttpOptions] = None
        if (
            parameter_model.config is not None
            and parameter_model.config.http_options is not None
        ):
            http_options = parameter_model.config.http_options

        request_dict = _common.convert_to_dict(request_dict)
        request_dict = _common.encode_unserializable_types(request_dict)

        response = self._api_client.request("get", path, request_dict, http_options)

        response_dict = {} if not response.body else json.loads(response.body)

        return_value = types.MemoryRevision._from_response(
            response=response_dict, kwargs=parameter_model.model_dump()
        )

        self._api_client._verify_response(return_value)
        return return_value

    def _list(
        self,
        *,
        name: str,
        config: Optional[types.ListAgentEngineMemoryRevisionsConfigOrDict] = None,
    ) -> types.ListAgentEngineMemoryRevisionsResponse:
        """
        Lists Agent Engine memory revisions.

        Args:
            name (str): Required. The name of the Agent Engine memory to list revisions for. Format:
                `projects/{project}/locations/{location}/reasoningEngines/{resource_id}/memories/{memory_id}`.
            config (ListAgentEngineMemoryRevisionsConfig):
                Optional. Additional configurations for listing the Agent Engine memory revisions.

        Returns:
            ListAgentEngineMemoryRevisionsResponse: The requested Agent Engine memory revisions.

        """

        parameter_model = types._ListAgentEngineMemoryRevisionsRequestParameters(
            name=name,
            config=config,
        )

        request_url_dict: Optional[dict[str, str]]
        if not self._api_client.vertexai:
            raise ValueError("This method is only supported in the Vertex AI client.")
        else:
            request_dict = _ListAgentEngineMemoryRevisionsRequestParameters_to_vertex(
                parameter_model
            )
            request_url_dict = request_dict.get("_url")
            if request_url_dict:
                path = "{name}/revisions".format_map(request_url_dict)
            else:
                path = "{name}/revisions"

        query_params = request_dict.get("_query")
        if query_params:
            path = f"{path}?{urlencode(query_params)}"
        # TODO: remove the hack that pops config.
        request_dict.pop("config", None)

        http_options: Optional[types.HttpOptions] = None
        if (
            parameter_model.config is not None
            and parameter_model.config.http_options is not None
        ):
            http_options = parameter_model.config.http_options

        request_dict = _common.convert_to_dict(request_dict)
        request_dict = _common.encode_unserializable_types(request_dict)

        response = self._api_client.request("get", path, request_dict, http_options)

        response_dict = {} if not response.body else json.loads(response.body)

        return_value = types.ListAgentEngineMemoryRevisionsResponse._from_response(
            response=response_dict, kwargs=parameter_model.model_dump()
        )

        self._api_client._verify_response(return_value)
        return return_value

    def list(
        self,
        *,
        name: str,
        config: Optional[types.ListAgentEngineMemoryRevisionsConfigOrDict] = None,
    ) -> Iterator[types.MemoryRevision]:
        """Lists Agent Engine memory revisions.

        Args:
            name (str):
                Required. The name of the Memory to list revisions for.
            config (ListAgentEngineMemoryRevisionsConfigOrDict):
                Optional. The configuration for the memories to list revisions.

        Returns:
            Iterable[MemoryRevision]: An iterable of memory revisions.
        """

        return Pager(
            "memory_revisions",
            functools.partial(self._list, name=name),
            self._list(name=name, config=config),
            config,
        )


class AsyncMemoryRevisions(_api_module.BaseModule):

    async def get(
        self,
        *,
        name: str,
        config: Optional[types.GetAgentEngineMemoryRevisionConfigOrDict] = None,
    ) -> types.MemoryRevision:
        """
        Gets an agent engine memory revision.

        Args:
            name (str): Required. The name of the Agent Engine memory revision to get. Format:
                `projects/{project}/locations/{location}/reasoningEngines/{resource_id}/memories/{memory_id}/revisions/{revision_id}`.
            config (GetAgentEngineMemoryRevisionConfig):
                Optional. Additional configurations for getting the Agent Engine memory revision.

        Returns:
            AgentEngineMemoryRevision: The requested Agent Engine memory revision.

        """

        parameter_model = types._GetAgentEngineMemoryRevisionRequestParameters(
            name=name,
            config=config,
        )

        request_url_dict: Optional[dict[str, str]]
        if not self._api_client.vertexai:
            raise ValueError("This method is only supported in the Vertex AI client.")
        else:
            request_dict = _GetAgentEngineMemoryRevisionRequestParameters_to_vertex(
                parameter_model
            )
            request_url_dict = request_dict.get("_url")
            if request_url_dict:
                path = "{name}".format_map(request_url_dict)
            else:
                path = "{name}"

        query_params = request_dict.get("_query")
        if query_params:
            path = f"{path}?{urlencode(query_params)}"
        # TODO: remove the hack that pops config.
        request_dict.pop("config", None)

        http_options: Optional[types.HttpOptions] = None
        if (
            parameter_model.config is not None
            and parameter_model.config.http_options is not None
        ):
            http_options = parameter_model.config.http_options

        request_dict = _common.convert_to_dict(request_dict)
        request_dict = _common.encode_unserializable_types(request_dict)

        response = await self._api_client.async_request(
            "get", path, request_dict, http_options
        )

        response_dict = {} if not response.body else json.loads(response.body)

        return_value = types.MemoryRevision._from_response(
            response=response_dict, kwargs=parameter_model.model_dump()
        )

        self._api_client._verify_response(return_value)
        return return_value

    async def _list(
        self,
        *,
        name: str,
        config: Optional[types.ListAgentEngineMemoryRevisionsConfigOrDict] = None,
    ) -> types.ListAgentEngineMemoryRevisionsResponse:
        """
        Lists Agent Engine memory revisions.

        Args:
            name (str): Required. The name of the Agent Engine memory to list revisions for. Format:
                `projects/{project}/locations/{location}/reasoningEngines/{resource_id}/memories/{memory_id}`.
            config (ListAgentEngineMemoryRevisionsConfig):
                Optional. Additional configurations for listing the Agent Engine memory revisions.

        Returns:
            ListAgentEngineMemoryRevisionsResponse: The requested Agent Engine memory revisions.

        """

        parameter_model = types._ListAgentEngineMemoryRevisionsRequestParameters(
            name=name,
            config=config,
        )

        request_url_dict: Optional[dict[str, str]]
        if not self._api_client.vertexai:
            raise ValueError("This method is only supported in the Vertex AI client.")
        else:
            request_dict = _ListAgentEngineMemoryRevisionsRequestParameters_to_vertex(
                parameter_model
            )
            request_url_dict = request_dict.get("_url")
            if request_url_dict:
                path = "{name}/revisions".format_map(request_url_dict)
            else:
                path = "{name}/revisions"

        query_params = request_dict.get("_query")
        if query_params:
            path = f"{path}?{urlencode(query_params)}"
        # TODO: remove the hack that pops config.
        request_dict.pop("config", None)

        http_options: Optional[types.HttpOptions] = None
        if (
            parameter_model.config is not None
            and parameter_model.config.http_options is not None
        ):
            http_options = parameter_model.config.http_options

        request_dict = _common.convert_to_dict(request_dict)
        request_dict = _common.encode_unserializable_types(request_dict)

        response = await self._api_client.async_request(
            "get", path, request_dict, http_options
        )

        response_dict = {} if not response.body else json.loads(response.body)

        return_value = types.ListAgentEngineMemoryRevisionsResponse._from_response(
            response=response_dict, kwargs=parameter_model.model_dump()
        )

        self._api_client._verify_response(return_value)
        return return_value

    async def list(
        self,
        *,
        name: str,
        config: Optional[types.ListAgentEngineMemoryRevisionsConfigOrDict] = None,
    ) -> AsyncPager[types.MemoryRevision]:
        """Lists Agent Engine memory revisions.

        Args:
            name (str):
                Required. The name of the Memory to list revisions for.
            config (ListAgentEngineMemoryRevisionsConfigOrDict):
                Optional. The configuration for the memories to list revisions.

        Returns:
            AsyncPager[MemoryRevision]: An async pager of memory revisions.
        """

        return AsyncPager(
            "memory_revisions",
            functools.partial(self._list, name=name),
            await self._list(name=name, config=config),
            config,
        )
